package com.kaiwukj.android.ufamily.mvp.ui.page.account.community;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerAccountComponent;
import com.kaiwukj.android.ufamily.di.module.AccountModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommunityResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.AccountContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.location.LocationUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

@Route(path = ARouterUrlKt.CommunityUpdateUrl)
public class CommunityUpdateActivity extends BaseMvpActivity<CommunityPresenter> implements AccountContract.CommunityView {

    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rv_community)
    RecyclerView rvCommunity;
    @BindView(R.id.container_left)
    ViewGroup containerLeft;

    private CommunityNearAdapter mAdapter;

    private boolean isFirst = true;

    @Autowired
    int pickAction;

    private Location lastLocation;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @OnClick(R.id.tv_reply)
    void reLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        //showLoading("正在获取位置...");
        //isFirst = true;
        //LocationUtils.refresh(12 * 1000, 20);
        if (lastLocation != null) {
            showLoading("正在请求...");
            tvCity.setText(LocationUtils.getLocality(lastLocation.getLatitude(), lastLocation.getLongitude()));
            mPresenter.fetchNearCommunity(lastLocation.getLatitude(), lastLocation.getLongitude());
            etSearch.setText("");
        }
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerAccountComponent.builder()
                .appComponent(appComponent)
                .accountModule(new AccountModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_community_near;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mPresenter.fetchCommunityByKeyword(etSearch.getText().toString().trim());
            }
            return false;
        });

        rvCommunity.setLayoutManager(new LinearLayoutManager(this));
        rvCommunity.addItemDecoration(new SpaceItemDecoration(1));
        mAdapter = new CommunityNearAdapter();
        rvCommunity.setAdapter(mAdapter);


        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            CommunityResult itemResult = (CommunityResult) adapter.getItem(position);
            if (itemResult != null) {
                if (pickAction == 1) {
                    containerLeft.setOnClickListener(v -> onBackPressedSupport());
                    Intent data = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", itemResult);
                    data.putExtras(bundle);
                    setResult(RESULT_OK, data);
                    finish();
                } else {
                    containerLeft.setVisibility(View.GONE);
                    showMessageOKCancel(this, itemResult.getCommunityName(), v ->
                            mPresenter.updateCommunity(itemResult.getId(), itemResult.getCommunityName())
                    );
                }
            }

        });


    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        // mPresenter.fetchNearCommunity(28.67360774, 115.94000816);
        showLoading("正在获取位置...");
        RxPermissions rxPermissions = new RxPermissions(this);
        subscribe(rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(g -> {
                    if (g) {
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        boolean isRegister = registerLocation();
                        if (!isRegister) {
                            showMessage("请打开定位服务");
                            LocationUtils.openGpsSettings();
                        }
                    }
                }));
    }

    @RequiresPermission(ACCESS_FINE_LOCATION)
    private boolean registerLocation() {
        return LocationUtils.register(8 * 1000, 20, new LocationUtils.OnLocationChangeListener() {
            @Override
            public void getLastKnownLocation(Location location) {
                lastLocation = location;
                LogUtils.d("getLastKnownLocation------------------>" + location.getLatitude() + ":" + location.getLongitude());
                tvCity.setText(LocationUtils.getLocality(location.getLatitude(), location.getLongitude()));
                if (isFirst) {
                    isFirst = false;
                    showLoading("正在请求...");
                    mPresenter.fetchNearCommunity(location.getLatitude(), location.getLongitude());
                }
            }

            @Override
            public void onLocationChanged(Location location) {
                lastLocation = location;
                LogUtils.d("location------------------>" + location.getLatitude() + ":" + location.getLongitude());
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }
        });
    }

    @Override
    public void onFetchNearCommunity(List<CommunityResult> results) {
        hideLoading();
        mAdapter.setList(results);
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == CommunityPresenter.UPDATE) {
            showMessage("更新社区成功");
            if (pickAction == 0) {
                ARouter.getInstance().build(ARouterUrlKt.MainRouterUrl).navigation();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationUtils.unregister();
    }

    @Override
    public void onBackPressedSupport() {
        if (pickAction == 1) {
            super.onBackPressedSupport();
        }
    }
}
